package com.key.controller.admin.assetManagement;

import com.key.common.R;
import com.key.common.dto.StocktakingAssetDTO;
import com.key.common.dto.StocktakingFormDTO;
import com.key.common.dto.StocktakingFormFindDTO;
import com.key.common.dto.StocktakingSurplusDTO;
import com.key.common.vo.StocktakingAssetsVO;
import com.key.common.vo.StocktakingFormDetailsVO;
import com.key.entity.StocktakingForm;
import com.key.service.StocktakingFormService;
import io.swagger.annotations.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @author wei
 * @create 2023-02-17 16:10
 */
@Controller
@Api(value = "盘点数据",tags = "盘点管理")
@RequestMapping("/stocktakingForm")
public class StocktakingFormController {

    @Autowired
    StocktakingFormService stocktakingFormService;

    /**
     * 新建(添加)盘点清单
     * @author wei
     * @param stocktakingFormDTO
     * @return
     */
    @RequestMapping(value = "/addStocktakingForm", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新建盘点",notes = "获取前端页面的信息以完成新建",httpMethod = "post", response = R.class)
    public R addStocktakingForm(@RequestBody @ApiParam(name = "StocktakingFormDTO",value = "新建盘点清单需要填入的属性",required = true) StocktakingFormDTO stocktakingFormDTO){
        R r;

        boolean result = stocktakingFormService.addStocktakingForm(stocktakingFormDTO);

        if(result){
            r = new R(200,"新建成功");
        }else {
            r = new R(500,"盘点范围内没有资产");
        }

        return r;
    }

    /**
     * 删除盘点清单
     * @author wei
     * @param sfNo
     * @return
     */
    @RequestMapping(value = "/removeStocktakingForm", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除盘点",notes = "通过前端传来的盘点单号删除盘点单",httpMethod = "post", response = R.class)
    @ApiImplicitParam(name = "sfNo",value = "盘点单号",required = true,dataType = "String",paramType = "query")
    public R removeStocktakingForm(@RequestParam(name = "sfNo") String sfNo){
        R r;

        boolean result = stocktakingFormService.removeStocktakingForm(sfNo);

        if(result){
            r = new R(200,"删除成功");
        }else {
            r = new R(500,"删除失败");
        }

        return r;
    }

    /**
     * 分页查询盘点单(含高级搜索)
     * @author wei
     * @param stocktakingFormFindDTO
     * @return
     */
    @RequestMapping(value = "/findStocktakingFormList", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查找盘点",notes = "通过参数分页查询",httpMethod = "post", response = R.class)
    public R findStocktakingFormList(@RequestBody @ApiParam(name = "StocktakingFormFindDTO",value = "查询盘点清单可能会用到的参数",required = true) StocktakingFormFindDTO stocktakingFormFindDTO){
        R r = new R();

        try{
            Map<String, Object> map = stocktakingFormService.findStocktakingForm(stocktakingFormFindDTO);
            List<StocktakingForm> stocktakingFormList = (List<StocktakingForm>) map.get("stocktakingFormList");
            Integer count = (Integer) map.get("count");

            r.setCode(200);
            r.setCount(count);
            r.setMsg("查询成功");
            r.setData(stocktakingFormList);
        }catch (Exception e){
            r.setCode(500);
            r.setMsg("后台代码异常");
        }

        return r;
    }

    /**
     * 查看详情
     * @author wei
     * @param sfNo
     * @return
     */
    @RequestMapping(value = "/stocktakingFormDetails", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "盘点单详情",notes = "根据前端返回的盘点单号查看详情",httpMethod = "get", response = R.class)
    @ApiImplicitParam(name = "sfNo",value = "盘点单号",required = true,dataType = "String",paramType = "query")
    public R stocktakingFormDetails(@RequestParam(name = "sfNo") String sfNo){
        R r = new R();
        try{
            StocktakingFormDetailsVO stocktakingFormDetailsVO = stocktakingFormService.findStocktakingFormDetailsVOBySfNo(sfNo);
            r.setCode(200);
            r.setMsg("查询成功");
            r.setData(stocktakingFormDetailsVO);
        }catch (Exception e){
            r.setCode(500);
            r.setMsg("后台代码异常");
        }
        return r;
    }

    /**
     * 回显分配的用户
     * @author wei
     * @param sfNo
     * @return
     */
    @RequestMapping(value = "/displayAssignedUsers", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "回显分配的用户",notes = "回显盘点单分配的用户",httpMethod = "get", response = R.class)
    @ApiImplicitParam(name = "sfNo",value = "盘点单号",required = true,dataType = "String",paramType = "query")
    public R displayAssignedUsers(@RequestParam(name = "sfNo") String sfNo){
        R r = new R();
        try{
            List<String> assignEmpsName = stocktakingFormService.findEmployeeBySfNo(sfNo);
            r.setCode(200);
            r.setMsg("查询成功");
            r.setData(assignEmpsName);
        }catch (Exception e){
            r.setCode(500);
            r.setMsg("后台代码异常");
        }
        return r;
    }

    /**
     * 修改分配的用户
     * @author wei
     * @param sfNo
     * @return
     */
    @RequestMapping(value = "/editAssignedUsers", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改分配的用户",notes = "修改盘点单分配的用户",httpMethod = "post", response = R.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sfNo",value = "盘点单号",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "assignEmpsName",value = "分配的用户",required = true,dataType = "String",paramType = "query",allowMultiple = true)
    })
    public R editAssignedUsers(@RequestParam(name = "sfNo") String sfNo,
                               @RequestParam(name = "assignEmpsName") List<String> assignEmpsName){
        R r;

        boolean result = stocktakingFormService.editAssignedUsers(sfNo, assignEmpsName);

        if(result){
            r = new R(200,"修改成功");
        }else {
            r = new R(500,"修改失败");
        }

        return r;
    }

    /**
     * 未盘点员工查询
     * @author wei
     * @param sfNo
     * @return
     */
    @RequestMapping(value = "/findIncompleteEmployees", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "未盘点员工查询",notes = "根据盘点单号查询未盘点完的员工",httpMethod = "get", response = R.class)
    @ApiImplicitParam(name = "sfNo",value = "盘点单号",required = true,dataType = "String",paramType = "query")
    public R findIncompleteEmployees(@RequestParam(name = "sfNo") String sfNo){
        R r = new R();

        try{
            List<Map<String, Object>> map = stocktakingFormService.findIncompleteEmployees(sfNo);
            r.setCode(200);
            r.setMsg("查询成功");
            r.setData(map);
        }catch (Exception e){
            r.setCode(500);
            r.setMsg("后台代码异常");
        }

        return r;
    }

    /**
     * 查询盘点单里的资产
     * @author wei
     * @param currentPage
     * @param pageSize
     * @param sfNo
     * @return
     */
    @RequestMapping(value = "/findStocktakingFormAssets", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询盘点单里的资产",notes = "通过盘点单号查询",httpMethod = "get", response = R.class)

    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage",value = "当前页",paramType = "query",dataType = "int",required = true),
            @ApiImplicitParam(name = "pageSize",value = "页的大小",paramType = "query",dataType = "int",required = true),
            @ApiImplicitParam(name = "sfNo",value = "盘点单号",paramType = "query",dataType = "String",required = true),
    })
    public R findStocktakingFormAssets(@RequestParam(name = "currentPage") Integer currentPage,
                                       @RequestParam(name = "pageSize") Integer pageSize,
                                       @RequestParam(name = "sfNo") String sfNo){
        R r = new R();

        try{
            Map<String, Object> map = stocktakingFormService.findStocktakingAssetsBySfNo(currentPage, pageSize, sfNo);

            List<StocktakingAssetsVO> stocktakingAssetsVOList = (List<StocktakingAssetsVO>) map.get("stocktakingAssetsVOList");
            Integer count = (Integer) map.get("count");

            r.setCode(200);
            r.setMsg("查询成功");
            r.setData(stocktakingAssetsVOList);
            r.setCount(count);
        }catch (Exception e){
            r.setCode(500);
            r.setMsg("后台代码异常");
        }

        return r;
    }

    /**
     * 修改盘点的资产
     * @author wei
     * @param stocktakingSurplusDTO
     * @return
     */
    @RequestMapping(value = "/editStocktakingAsset", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改盘点的资产",notes = "根据盘点单号和资产id和填入信息修改盘点的资产",httpMethod = "post", response = R.class)
    public R editStocktakingAsset(@RequestBody @ApiParam(name = "StocktakingAssetDTO",value = "删除或者修改时需要传到后台的参数",required = true) StocktakingSurplusDTO stocktakingSurplusDTO){
        R r;
        System.out.println(stocktakingSurplusDTO);
        boolean result = stocktakingFormService.editStocktakingAsset(stocktakingSurplusDTO);

        if(result){
            r = new R(200,"修改成功");
        }else {
            r = new R(500,"修改失败");
        }

        return r;
    }

    /**
     * 添加盘盈
     * @author wei
     * @param stocktakingAssetDTO
     * @return
     */
    @RequestMapping(value = "/addStocktakingSurplus", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "添加盘盈",notes = "根据盘点单号和资产id和填入信息添加盘盈",httpMethod = "post", response = R.class)
    public R addStocktakingSurplus(@RequestBody @ApiParam(name = "StocktakingAssetDTO",value = "添加盘盈需要填入的属性",required = true) StocktakingAssetDTO stocktakingAssetDTO){
        R r;

        boolean result = stocktakingFormService.addStocktakingSurplus(stocktakingAssetDTO);

        if(result){
            r = new R(200,"添加成功");
        }else {
            r = new R(500,"添加失败");
        }

        return r;
    }

    /**
     * 删除盘盈
     * @author wei
     * @param stocktakingSurplusDTO
     * @return
     */
    @RequestMapping(value = "/removeStocktakingSurplus", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除盘盈",notes = "根据盘点单号和资产id删除盘盈",httpMethod = "post", response = R.class)
    public R removeStocktakingSurplus(@RequestBody @ApiParam(name = "StocktakingAssetDTO",value = "删除或者修改时需要传到后台的参数",required = true) StocktakingSurplusDTO stocktakingSurplusDTO){
        R r;

        boolean result = stocktakingFormService.removeStocktakingSurplus(stocktakingSurplusDTO);

        if(result){
            r = new R(200,"删除成功");
        }else {
            r = new R(500,"删除失败");
        }

        return r;
    }


    /**
     * 提交盘点
     * @author wei
     * @param sfNo
     * @return
     */
    @RequestMapping(value = "/submitStocktaking", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "提交盘点单",notes = "获取盘点单id，提交盘点单",httpMethod = "post", response = R.class)
    @ApiImplicitParam(name = "sfNo",value = "盘点单号",required = true,dataType = "String",paramType = "query")
    public R submitStocktaking(@RequestParam(name = "sfNo") String sfNo){
        R r;

        boolean result = stocktakingFormService.submitStocktaking(sfNo);

        if(result){
            r = new R(200,"提交成功");
        }else {
            r = new R(500,"盘点单内还有资产未盘点完");
        }

        return r;
    }

    /**
     * 下载
     * @author wei
     * @param sfNo
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "下载(内层查询)",notes = "下载盘点单",httpMethod = "get", response = R.class)
    @ApiImplicitParam(name = "sfNo",value = "盘点单号",required = true,dataType = "String",paramType = "query")
    public void download(@RequestParam(name = "sfNo") String sfNo,HttpServletRequest request, HttpServletResponse response) throws Exception {
        HSSFWorkbook workBook = stocktakingFormService.getWorkBook(sfNo);
        String userAgent = request.getHeader("User-Agent");

        //excel文件名
        String fileName = "盘点资产表"+System.currentTimeMillis()+".xls";
        // 针对IE或者以IE为内核的浏览器：
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器的处理：
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        //响应到客户端
        try {
            OutputStream os = response.getOutputStream();
            response.setContentType("application/x-xls;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            workBook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出excel表格
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出excel表格(外层查询)",notes = "导出excel表格",httpMethod = "get", response = R.class)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HSSFWorkbook workBook = stocktakingFormService.getWorkBook();
        String userAgent = request.getHeader("User-Agent");

        //excel文件名
        String fileName = "盘点清单表"+System.currentTimeMillis()+".xls";
        // 针对IE或者以IE为内核的浏览器：
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器的处理：
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        //响应到客户端
        try {
            OutputStream os = response.getOutputStream();
            response.setContentType("application/x-xls;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            workBook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}